import { resolve } from 'aurelia';
import { IRouter } from '@aurelia/router';
import { Home } from './pages/home/home';
import { SingleConvert } from './pages/single-convert/single-convert';
import { BatchConvert } from './pages/batch-convert/batch-convert';
import { FormatSettings } from './pages/format-settings/format-settings';
import { ConversionHistory } from './pages/conversion-history/conversion-history';
import { Help } from './pages/help/help';

export class MyApp {
  static title = '文档格式转换器 - Word/Markdown/PDF互转工具';
  
  static routes = [
    {
      path: '',
      component: Home,
      title: '首页'
    },
    {
      path: 'single-convert',
      component: SingleConvert,
      title: '单文件转换'
    },
    {
      path: 'batch-convert',
      component: BatchConvert,
      title: '批量转换'
    },
    {
      path: 'format-settings',
      component: FormatSettings,
      title: '格式设置'
    },
    {
      path: 'conversion-history',
      component: ConversionHistory,
      title: '转换历史'
    },
    {
      path: 'help',
      component: Help,
      title: '帮助文档'
    }
  ];

  constructor() {
    this.router = resolve(IRouter);
    this.currentRoute = '';
    this.navigationItems = [
      { id: 'home', title: '首页', icon: '🏠', path: '' },
      { id: 'single-convert', title: '单文件转换', icon: '📄', path: 'single-convert' },
      { id: 'batch-convert', title: '批量转换', icon: '📚', path: 'batch-convert' },
      { id: 'format-settings', title: '格式设置', icon: '⚙️', path: 'format-settings' },
      { id: 'conversion-history', title: '转换历史', icon: '📋', path: 'conversion-history' },
      { id: 'help', title: '帮助文档', icon: '❓', path: 'help' }
    ];
  }

  attached() {
    // 组件附加后初始化路由状态
    this.initializeRouteState();
  }

  initializeRouteState() {
    if (this.router) {
      // 设置初始路由状态
      this.updateCurrentRoute();
      
      // 监听路由变化（如果支持的话）
      if (this.router.addHook) {
        this.router.addHook('transformFromUrl', () => {
          // 延迟更新以确保路由已完成
          setTimeout(() => this.updateCurrentRoute(), 0);
        });
      }
    } else {
      console.warn('Router not available in initializeRouteState');
      // 如果路由器不可用，尝试手动导航到首页
      this.currentRoute = 'home';
    }
  }

  updateCurrentRoute() {
    try {
      if (!this.router) {
        return;
      }
      
      // 获取当前路径
      const currentPath = window.location.hash.replace('#/', '') || '';
      const activeItem = this.navigationItems.find(item => item.path === currentPath);
      this.currentRoute = activeItem ? activeItem.id : 'home';
    } catch (error) {
      console.warn('Error updating current route:', error);
      this.currentRoute = 'home';
    }
  }

  async setActiveRoute(routeId, event) {
    if (event) {
      event.preventDefault();
    }
    
    try {
      const navItem = this.navigationItems.find(item => item.id === routeId);
      if (navItem) {
        if (this.router) {
          await this.router.load(navItem.path);
          this.currentRoute = routeId;
        } else {
          // 如果路由器不可用，手动更新 URL
          console.warn('Router not available, updating URL manually');
          window.location.hash = navItem.path ? `#/${navItem.path}` : '#/';
          this.currentRoute = routeId;
        }
      } else {
        console.warn('Navigation failed - navItem not found:', routeId);
      }
    } catch (error) {
      console.error('Navigation error:', error);
      // 如果路由失败，尝试回退到首页
      if (routeId !== 'home') {
        try {
          if (this.router) {
            await this.router.load('');
          } else {
            window.location.hash = '#/';
          }
          this.currentRoute = 'home';
        } catch (fallbackError) {
          console.error('Fallback navigation failed:', fallbackError);
        }
      }
    }
  }
}
